import { defineEventHandler, readMultipartFormData, createError } from "h3";
import { fileUploadService } from "server/utils/fileUpload";

export default defineEventHandler(async (event) => {
  try {
    const user = event.context.user;

    // 读取表单数据
    const formData = await readMultipartFormData(event);
    if (!formData) {
      throw createError({
        statusCode: 400,
        statusMessage: "未找到上传文件",
      });
    }

    // 查找文件字段和分类字段
    let fileData: any = null;
    let category = "default";

    for (const field of formData) {
      if (field.name === "file" && field.data) {
        fileData = field;
      } else if (field.name === "category" && field.data) {
        category = field.data.toString("utf-8");
      }
    }

    if (!fileData) {
      throw createError({
        statusCode: 400,
        statusMessage: "未找到文件字段",
      });
    }

    // 上传文件
    const uploadResult = await fileUploadService.uploadFile(
      {
        buffer: fileData.data,
        originalname: fileData.filename || "unknown",
        mimetype: fileData.type || "application/octet-stream",
        size: fileData.data.length,
      },
      category,
      user.userId
    );

    if (!uploadResult.success) {
      throw createError({
        statusCode: 400,
        statusMessage: uploadResult.error || "文件上传失败",
      });
    }

    return {
      success: true,
      data: {
        id: uploadResult.file?.id,
        url: uploadResult.url,
        fileName: uploadResult.file?.file_name,
        originalName: uploadResult.file?.original_name,
        fileSize: uploadResult.file?.file_size,
        mimeType: uploadResult.file?.mime_type,
        category: uploadResult.file?.category,
        storageType: uploadResult.file?.storage_type,
      },
    };
  } catch (error: any) {
    console.error("文件上传接口错误:", error);

    if (error.statusCode) {
      throw error;
    }

    throw createError({
      statusCode: 500,
      statusMessage: error.message || "服务器内部错误",
    });
  }
});
